package Root;

import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.TreeMap;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.Timer;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseListener;
import org.jnativehook.mouse.NativeMouseMotionListener;

import com.sun.corba.se.spi.activation._ActivatorStub;
import com.sun.media.sound.AlawCodec;

import A002_Obrazek._A_OBRAZEK;
import Analizer.MouseMove_TM;
import GUI.DO;
import GUI._PanelObszar;
import Linki._A_LADUJ_SERtoBUFEIMG;
import Linki._A_Path;
import OBSZARY_def.GO;
import OBSZARY_def.MM;
import OBSZARY_def.hpGO;
import OBSZARY_def.ob;
import OBSZARY_def.R4;
import OBSZARY_def._MM_obszarRuchu;
import OBSZARY_def._obszar;
import OBSZARY_def._obszarR4;
import OBSZARY_def.iobszarR4;
import OBSZARY_def.sheldGO;

public class DO_Start_AObrazek extends _A_LADUJ_SERtoBUFEIMG implements _zminne, 
		NativeMouseListener, NativeMouseMotionListener, NativeKeyListener {
	
	
	public synchronized boolean is_play() { return _play; }
	public synchronized void set_play(boolean _play) {	this._play = _play;}
	public synchronized boolean get_play() {return this._play;}
	private boolean _play;
	
	public static Robot rob = null;
	public static BufferedImage buf = null; //testowe na maka
	public static DO _window;
	public static Rectangle _AktywnyObszarMonitora = null;
	public static Rectangle _FullSizesAllDewicesScreen = null;
	//public static _A_Path _Path;
	public MouseMove_TM _mm ;
	//public static Hashtable<String, _A_OBRAZEK> _LinkiObrazkow;
	public static _B_SZUKAJ_BUFF_A_OBRAZEK _szukacz;
	//++++++++++++++++++++++++++++++++++++++++++++++++
	public static TreeMap<Integer, _punktData> _DaneINT,a;
	public TreeMap<String, _punktData> _DaneSTR;
	public static TreeMap<String, _punktData> b;
	
	public static HashMap<String, _obszarR4> _Obszary,c;// klasy typu _obszar

	public static int XStatek = 0;
	public static int YStatek = 0;
	
	public DO_Start_AObrazek() {
		super();
		try {
			GlobalScreen.registerNativeHook();
		} catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
		}
		//System.out.println("Hook state: "+ GlobalScreen.isNativeHookRegistered());
		 
		//globEvent ae = new globEvent();
	       GlobalScreen.getInstance().addNativeMouseListener(this );
	       GlobalScreen.getInstance().addNativeMouseMotionListener(this);
	       GlobalScreen.getInstance().addNativeKeyListener(this);
		
	    try {
	   		rob = new Robot();
	   	} catch (AWTException e) {
	   		// TODO Auto-generated catch block
	   		e.printStackTrace();
	   	}
	       
	    _DaneSTR = new TreeMap<>();
	    _Obszary = new HashMap<String, _obszarR4>();
		_AktywnyObszarMonitora = UstawAktywnyMonitor();
		_FullSizesAllDewicesScreen = getFullSizesAllDevicesScreen();
		_mm = new MouseMove_TM(iGlobalPath+iKatSys +"A001_SCHEMATY_MYSZY/",
				_FullSizesAllDewicesScreen, this);
		_szukacz = new _B_SZUKAJ_BUFF_A_OBRAZEK(this._AktywnyObszarMonitora);
		//_z2 = new _zrzut2();
		//_z2.start();
		
		Timer ti = new Timer(5000, new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				//System.out.println ("actionWindow");
				DO_Start_AObrazek._window.frame.repaint();
				DO_Start_AObrazek._window.frame.revalidate();
			}
		});
		ti.start();
		
		
	}
	
	_MM_obszarRuchu obruchu;

	public void _InitAllObszary (){
		//_szukacz._FF_String(_zrzut(null), _DaneSTR, 0, 0, _ListaObrazków);
		_Obszary.clear();
		//GO go;
		set_play(false);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		obruchu = new _MM_obszarRuchu("minimapa", this);
		_Obszary.put("minimapa", obruchu);
			
		//hpGO _ststekHP = new hpGO("hp", this);
		//_Obszary.put("hp", _ststekHP);
		
		//sheldGO _ststekSH = new sheldGO("sheld", this);
		//_Obszary.put("sheld", _ststekSH);

		for(String a:_Obszary.keySet()){
			_Obszary.get(a).aktywujObszar();
			_Obszary.get(a).go();
			new _PanelObszar(_Obszary.get(a), null);
		}

		
		//System.out.println("rectangle R2 " + R4._obszar.toString());
		//minimapa.test();
		//minimapa._akualizujDane();
		
		//_mm.iMouseMove(minimapa.X1, minimapa.Y1, 1500, true);
		//_mm.iMouseMove(minimapa.X1, minimapa.Y2, 1500, false);
		//_mm.iMouseMove(minimapa.X2,minimapa.Y1, 1500, false);
		//_mm.iMouseMove(minimapa.X2, minimapa.Y2, 1500, false);
		
		_window.frame.setVisible(true);
		wirking();		
	}
	
	public void wirking(){
		 set_play(true);
		 TreeMap<Integer, _punktData> pp;
		 TreeMap<String, _punktData> ps = new TreeMap<String, _punktData>();
		 _punktData punkt;
		// wspolrzedne poprzeniego klikniecia w minimape
		 int xMM_old = 0, yMM_old = 0, timeMM = 1000, odcinekMM = 0;
		 long timeMMold = 0;
		 final int T1 = 340; // szybkosc pojazdu
		 BufferedImage bufer;
		 
		 
		while(true){
			while(is_play()){
				bufer = _zrzut3(_AktywnyObszarMonitora);
				//bufer = null;
				ps = _szukacz._FF_String_1obraz (bufer, null, 0, 0, _ListaObrazków.get("SHELD80"));
				if(ps.size()>0){
					pp = _szukacz._FF_Integer_1obraz(bufer, null, _AktywnyObszarMonitora.x+_AktywnyObszarMonitora.width/2,_AktywnyObszarMonitora.y+ _AktywnyObszarMonitora.height/2, _ListaObrazków.get("pall1"));
					if (pp.size() > 0){
						punkt = pp.firstEntry().getValue();
						if (punkt.iodcinek > 0){
							_mm.iMouseMove(punkt.ix+_mm.int_RandomMinMax(1,10), punkt.iy+_mm.int_RandomMinMax(1,10), 0, true);
							try {Thread.sleep(1800);} catch (InterruptedException e) { e.printStackTrace();}
						}
					}else if (pp.size() <= 0 && System.currentTimeMillis()> timeMMold)  {
						int x1 =_mm.int_RandomMinMax (obruchu._obszarRuchu.x, obruchu._obszarRuchu.x+obruchu._obszarRuchu.width);
						int y1 = _mm.int_RandomMinMax (obruchu._obszarRuchu.y, obruchu._obszarRuchu.y + obruchu._obszarRuchu.height);
						if (xMM_old > obruchu.X1 && xMM_old < obruchu.X2 && yMM_old > obruchu.Y1 && yMM_old < obruchu.Y2){
							odcinekMM = _szukacz.odcinek(x1, y1, xMM_old, yMM_old);
							//timeMM =  (Math.abs(odcinekMM) * 1000 / T1)*100;
							timeMM =  (Math.abs(odcinekMM) * 1000 / T1)*_mm.int_RandomMinMax(100,400);
							System.out.println ("odcinekMM/ " + odcinekMM + " timeMM/ " + timeMM);
						}
						xMM_old=x1; 
						yMM_old=y1;
						timeMMold = System.currentTimeMillis() + timeMM;
						//System.out.println ("odcinek x=" + x1 + " y= " + y1);
						
						_mm.iMouseMove(x1, y1, 0, true);
					}
				}


				try {Thread.sleep(500);} catch (InterruptedException e) { e.printStackTrace();}
			}
		}
	
	}
	
	class czasomerz {
		
	}
	
	
	synchronized void pauza(){
		//if (!get_play()) return;
		set_play(false); 
		
    	Object[] options = {"play", "stop"};
    	
		int JP = JOptionPane.showOptionDialog(_window.frame, "przerwales", "PLAY/STOP",
				JOptionPane.DEFAULT_OPTION, JOptionPane.NO_OPTION, null, options, options[1]);

		switch(JP){
		case 0:
			set_play(true);
			break;
		case 1:
			pauza();
			break;
		default:
			pauza();
			break;
		}
	}
	
	
	public Rectangle getFullSizesAllDevicesScreen(){
		Rectangle tmp = new Rectangle();
	    GraphicsEnvironment env = GraphicsEnvironment. getLocalGraphicsEnvironment(); 
	    int devicesilosc = env.getScreenDevices().length;
	    GraphicsDevice devices[] = env.getScreenDevices();
	    
	    	System.out.println("Jest wiecej Ekranow - " + devicesilosc );
	    	for (GraphicsDevice a: devices){
	    		tmp.add(a.getDefaultConfiguration().getBounds());
	    	}
	    
	    
		System.out.println("FullSizesAllDewicesScreen " + tmp.toString());
		return tmp;		
	}
	
	private Rectangle UstawAktywnyMonitor() {
		Integer _NRaktywnegoMonitora = 0;
	    GraphicsEnvironment env = GraphicsEnvironment. getLocalGraphicsEnvironment(); 
	    int devicesilosc = env.getScreenDevices().length;
	    GraphicsDevice devices[] = env.getScreenDevices();
	    if (devicesilosc >1){
	    	
	    	System.out.println("Jest wiecej Ekranow - " + devicesilosc );
	    	for (GraphicsDevice a: devices){
	    		System.out.println("getBounds() " + a.getDefaultConfiguration().getBounds());
	    		System.out.println("getDevice() " + a.getDefaultConfiguration().getDevice().getIDstring());
	            System.out.println("Width "+a.getDisplayMode().getWidth());
	            System.out.println("Height "+a.getDisplayMode().getHeight()); 
	    	}
	    	
	    	Object[] options = new Object[devicesilosc];
	    	for (int a=0; a<options.length; a++){
				 String jp = devices [a].getDefaultConfiguration().getDevice().getIDstring().toUpperCase();
				 options[a] = jp;
	    	}
			int JP = JOptionPane.showOptionDialog(null, "JEST WIECEJ EKRANOW", "Wybierz ekran",
					JOptionPane.DEFAULT_OPTION, JOptionPane.NO_OPTION, null, options, options[0]);

			 //System.out.println("JP "+ JP);
			switch(JP){
			case 0:
				_NRaktywnegoMonitora = 0;
				break;
			case 1:
				_NRaktywnegoMonitora = 1;
				break;
			default:
				_NRaktywnegoMonitora = 0;
				break;
			}
	    }
	    //_AktywnyObszarMonitora = devices[_NRaktywnegoMonitora].getDefaultConfiguration().getBounds();
		return devices[_NRaktywnegoMonitora].getDefaultConfiguration().getBounds();
	}
	
	

	
	public synchronized BufferedImage _zrzut3 (Rectangle rec){
		//System.out.println ("Brak obrazu zrzutu, wykonuje wlasny");
		if (this.buf != null && rec == null) {
			return buf;
		} else if (this.buf != null && rec != null){
			rec.add(_AktywnyObszarMonitora.x, _AktywnyObszarMonitora.y);
			BufferedImage buff = new BufferedImage(rec.width, rec.height, 5);
			for (int y=rec.y, sy=0; y<rec.y+rec.height; y++,sy++){
				for (int x=rec.x, sx=0; x<rec.x+rec.width; x++,sx++){
					buff.setRGB(sx, sy, buf.getRGB(x, y));
				};
			};
			return buff;
		} else if (this.buf == null && rec != null){
			rec.add(_AktywnyObszarMonitora.x, _AktywnyObszarMonitora.y);
			return rob.createScreenCapture( (rec) );
		} else return rob.createScreenCapture(_AktywnyObszarMonitora);
	}
	


	public static void main(String[] args) {
		
		
/*		//===============================================================================================
		//======== Inicjalizacja  linkow ================================================================
		//===============================================================================================
		_A_Path _Path = new _A_Path();
		//===============================================================================================
		_A_SzukaneSERtoBUFEIMG _initL = new _A_SzukaneSERtoBUFEIMG();
		
		
		//++++++++++++++DO TESTU ZURZUT++++++++++++++++++++
		
		//===============================================================================================
		//======== To sa zane do uzyskania tablic do testow Obrazek int [] i zrzut=======================
		//===============================================================================================
		//String Obrazek_test = "f:/006-JAVA/DO/PC/A004_DO-bot/SET/_PC/ObrazDoTestu/zrzut_obrazek2.bmp";
		String Obrazek_test = _A_Path.iGlobalPath + "SET/ObrazDoTestu/mapa1.bmp";
		BufferedImage buf = null;
		try {
			buf = ImageIO.read(new File(Obrazek_test));
		} catch (IOException e) {
			System.err.println("BRAK OlBRAZKA buffered image informacja z _A_DaneObrazka");
		}

		_B_SzukaczBUFF_A_OBRAZEK _szukacz = new _B_SzukaczBUFF_A_OBRAZEK();

		
		//===============================================================================================
		Rectangle rec2 = new Rectangle(0, 0, 300, 300);


		_szukacz._FF (null,_initL._Szukane_5_3.get("MINIMAPA"), 0, 0, 20, 0, false);
		_szukacz._FF (null,_initL._Szukane_5_3.get("PALLADIUM"), 0, 0, 30, 0, false);
		_szukacz._FF (null,_initL._Szukane_5_3.get("STATEKDANE"), 0, 0, 30, 0, false);*/

		String Obrazek_test = "/Volumes/BackupA/mapa.bmp";
		String Obrazek_test_PC = "I:/mapa.bmp";
		try {
			buf = ImageIO.read(new File(Obrazek_test));
		} catch (IOException e) {
			System.err.println("BRAK OBRAZKA buffered image informacja z _A_DaneObrazka");
			buf=null;
			try {
				buf = ImageIO.read(new File(Obrazek_test_PC));
			} catch (IOException e1) {
				System.err.println("BRAK OBRAZKA buffered image informacja z _A_DaneObrazka");
				buf=null;
			}
		}
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					_window = new DO();
					//window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	

		new DO_Start_AObrazek()._InitAllObszary();




		
	}

	@Override
	public void nativeKeyPressed(NativeKeyEvent arg0) {
	if (arg0.getKeyCode() == KeyEvent.VK_ESCAPE){ 
		//GlobalScreen.unregisterNativeHook();
		//System.runFinalization();
		//System.exit(-1);	
		pauza();
		}	
	}

	@Override
	public void nativeKeyReleased(NativeKeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void nativeKeyTyped(NativeKeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void nativeMouseDragged(NativeMouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void nativeMouseMoved(NativeMouseEvent arg0) {
		
	}

	@Override
	public void nativeMouseClicked(NativeMouseEvent arg0) {

		
	}

	@Override
	public void nativeMousePressed(NativeMouseEvent arg0) {

		
	}

	@Override
	public void nativeMouseReleased(NativeMouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	

}


